<template>
  <div class="wrap-container">
    <div class="flex">
      <div class="detail_l">
        <div class="bg-white py-3 px-4">
          <div class="flex justify-between">
            <div class="manage_tit">
              <div class="line"></div>
              <p>场地审核详情</p>
            </div>
            <div class="approval_btn">
              <template v-if="approvalStatus == 0">
                <template v-hasPermi="['sys:approval:btn_site_approval']">
                  <el-button type="primary" @click="handleApprove">通过</el-button>
                  <el-button type="warning" @click="handleRejects">驳回</el-button>
                </template>
              </template>
              <el-button @click="goBack">返回</el-button>
            </div>
          </div>
        </div>
        <div class="block_item">
          <div class="block_top">
            <p>场馆基本信息</p>
          </div>
          <div class="block_cont">
            <el-row :gutter="32" class="flex flex-nowrap">
              <el-col :span="8">
                <div>
                  <p><span>门店名称：</span>{{ stadiumInfo.stadiumName }}</p>
                </div>
                <div>
                  <p><span>场馆类型：</span>{{ stadiumInfo.stadiumType }}</p>
                </div>
                <div>
                  <p>
                    <span>营业时间：</span>工作日 {{ stadiumInfo.workDate }} 节假日
                    {{ stadiumInfo.legalDate }}
                  </p>
                </div>
              </el-col>
              <el-col :span="8">
                <div>
                  <p><span>门店电话：</span>{{ stadiumInfo.phone }}</p>
                </div>
                <div>
                  <p><span>门店地址：</span>{{ stadiumInfo.gdAddress }}</p>
                </div>
                <div>
                  <p><span>场馆标签：</span>{{ stadiumInfo.stadiumLabel }}</p>
                </div>
              </el-col>
              <el-col :span="8">
                <div>
                  <p><span>默认价格：</span>{{ stadiumInfo.isDefaultPrice == 1 ? '是' : '否' }}</p>
                </div>
                <div>
                  <p><span>退款时限：</span>{{ stadiumInfo.cancelHours }}小时</p>
                </div>
                <div>
                  <p><span>提前核销时间：</span>{{ stadiumInfo.writeMinutes }}分钟</p>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="block_top mt-6px">
            <p>场地看板信息</p>
          </div>
          <el-table
            :data="tableData"
            style="width: 100%"
            :span-method="arraySpanMethod"
            border
            v-loading="loading"
          >
            <el-table-column prop="type" label="场地类型" width="100"></el-table-column>
            <el-table-column prop="siteName" label="场地名称"></el-table-column>
            <el-table-column prop="isStandard" label="场地标准" width="90">
              <template #default="{ row }">
                <span>{{ row.isStandard == 0 ? '标准场' : '非标准场' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="siteNature" label="场地性质" width="90">
              <template #default="{ row }">
                <span>{{ row.siteNature == 0 ? '全场' : '半场' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="isIndependence" label="用户性质" width="90">
              <template #default="{ row }">
                <span>{{ row.isIndependence == 1 ? '散客' : '非散客' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="orderInstructions"
              label="使用说明"
              :formatter="formatter"
            ></el-table-column>
            <el-table-column prop="price" label="价格" width="100">
              <template #default="{ row }">
                <div class="flex justify-center">
                  <span>{{ row.price }}</span>
                  <el-tag
                    size="small"
                    class="ml-1"
                    v-if="row.isIndependence == 1 && row.defaultPrice == 1"
                    >默认</el-tag
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" :formatter="formatter"></el-table-column>
            <el-table-column prop="siteLong" label="场地长度" width="90"></el-table-column>
            <el-table-column prop="siteWide" label="场地宽度" width="90"></el-table-column>
            <el-table-column prop="siteArea" label="场地面积" width="90"></el-table-column>
            <el-table-column
              prop="siteSpecification"
              label="适用规格"
              :formatter="formatter"
            ></el-table-column>
            <el-table-column prop="enable" label="场地状态">
              <template #default="{ row }">
                <span>{{ row.enable == 0 ? '停用' : '启用' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="detail_r">
        <div class="order_track">
          <div class="order_top">
            <div class="manage_tit">
              <div class="line"></div>
              <p>场地看板审批流程</p>
            </div>
          </div>
          <div class="track_list">
            <div class="track_item" v-for="item in recordList" :key="item.id">
              <p class="create_time">{{ item.createTime }}</p>
              <div class="track_cont">
                <p v-if="item.approval == 0">{{ item.remark }}</p>
                <template v-else>
                  <p>
                    {{ item.createUser }}
                    <span class="text-color-808080">审核</span>
                    <span
                      :class="[item.approval == 1 ? 'text-color-00BAAD' : 'text-color-D43030']"
                      >{{ item.approval == 1 ? '通过' : '驳回' }}</span
                    >
                  </p>
                  <p class="text-color-808080 text-xs mt-2px" v-if="item.approval == 2">
                    说明：{{ item.approvalRemark }}
                  </p>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <reject-reson
      ref="rejectResonRef"
      :stadiumId="stadiumId"
      :pageType="'site'"
      :rejectList="rejectList"
      v-model:check-list="checkList"
    ></reject-reson>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getApprovalSiteDetail, approvalSiteByStadiumId } from '@/api/site/site'
import rejectReson from '@/components/Approval/rejectReson.vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { useUserStore } from '@/store/modules/user'

// 定义类型
interface StadiumInfo {
  stadiumName: string
  stadiumType: string
  workDate: string
  legalDate: string
  phone: string
  gdAddress: string
  stadiumLabel: string
  isDefaultPrice: number
  cancelHours: number
  writeMinutes: number
}

interface TableDataItem {
  type: string
  siteName: string
  isStandard: number
  siteNature: number
  isIndependence: number
  orderInstructions: string
  price: string
  remark: string
  siteLong: string
  siteWide: string
  siteArea: string
  siteSpecification: string
  enable: number
  approval: number
  defaultPrice: number
}

interface RecordItem {
  id: number
  createTime: string
  remark: string
  approval: number
  createUser: string
  approvalRemark: string
}

interface RejectItem {
  id: number
  name: string
}

// 使用 vue-router 和 store
const route = useRouter()
const router = useRouter()
const store = useStore()

// 响应式数据
const loading = ref(false)
const stadiumId = ref<number | null>(null)
const stadiumInfo = ref<Partial<StadiumInfo>>({})
const tableData = ref<TableDataItem[]>([])
const spanObj = ref<any>({})
const recordList = ref<RecordItem[]>([])
const approvalStatus = ref<number | null>(null)

// 组件引用
const rejectResonRef = ref<InstanceType<typeof rejectReson> | null>(null)

const spanArr = ['type', 'siteName'] // 表格中的列名
const otherSpan = [
  'isStandard',
  'siteNature',
  'isIndependence',
  'orderInstructions',
  'siteLong',
  'siteWide',
  'siteArea',
  'siteSpecification',
]

const rejectList = [
  { id: 1, name: '场地命名不规范‌‌' },
  { id: 2, name: '时段定价冲突‌' },
  { id: 3, name: '场地类型混用' },
  { id: 4, name: '其他原因' },
]
const checkList = ref<any[]>([])

// 方法定义
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getApprovalSiteDetail({
      stadiumId: stadiumId.value,
    })
    stadiumInfo.value = data.stadium
    tableData.value = data.priceList
    approvalStatus.value = tableData.value?.[0]?.approval || null
    recordList.value = data.recordList
    getSpanArr(tableData.value)
    if (stadiumInfo.value.stadiumLabel) {
      stadiumInfo.value.stadiumLabel = stadiumInfo.value.stadiumLabel.replace(',', '、')
    }
  } finally {
    loading.value = false
  }
}

// getSpanArr方法
const getSpanArr = (data: any) => {
  if (!data || data.length === 0) return

  spanArr.forEach((key) => {
    let count = 0
    spanObj.value[key] = []

    data.forEach((item: any, index: number) => {
      if (index === 0) {
        spanObj.value[key]!.push(1)
      } else {
        // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
        if (item[key] === data[index - 1][key]) {
          spanObj.value[key][count] += 1
          spanObj.value[key].push(0)
        } else {
          // 如果当前行和上一行其值不相等
          count = index // 记录当前位置
          spanObj.value[key].push(1) // 重新push 一个 1
        }
      }
    })
  })
}

const arraySpanMethod: Fn = ({ row, column, rowIndex, columnIndex }: any) => {
  // 判断列的属性
  if (column.property == 'type' || column.property == 'siteName') {
    // 判断其值是不是为0
    const spanValue = spanObj.value[column.property]
    if (spanValue && spanValue[rowIndex]) {
      return [spanValue[rowIndex], 1]
    } else {
      return [0, 0]
    }
  } else if (otherSpan.includes(column.property)) {
    const siteNameSpanValue = spanObj.value['siteName']
    if (siteNameSpanValue && siteNameSpanValue[rowIndex]) {
      return [siteNameSpanValue[rowIndex], 1]
    } else {
      return [0, 0]
    }
  }
  return [1, 1]
}

// 通过审批
const handleApprove = () => {
  ElMessageBox.confirm(`是否确认通过该场地的审批？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const params = {
        stadiumId: stadiumId.value,
        approvalStatus: 1,
        approvalUserId: store.state.user.id,
        approvalUserName: store.state.user.name,
      }
      approvalSiteByStadiumId(params).then(() => {
        ElMessage.success('操作成功')
        router.go(-1)
      })
    })
    .catch(() => {})
}

// 驳回审批
const handleRejects = () => {
  if (rejectResonRef.value) {
    rejectResonRef.value.showRejectModal = true
    // rejectResonRef.value.checkList = []
    checkList.value = []
  }
}

// 选择驳回原因
const changeReject = () => {
  // 这个方法在模板中没有被使用，但保留在代码中以维持功能完整性
}

const formatter = (row: any, column: any, cellValue: any) => {
  // 如果单元格值为空或为 null，返回 '--'
  return cellValue || '--'
}

// 返回
const goBack = () => {
  router.go(-1)
}

// 生命周期
onMounted(() => {
  stadiumId.value = Number(route.currentRoute.value.query.id as string) || null
  getList()
})
</script>

<style lang="scss" scoped>
.wrap-container {
  .detail_l {
    flex: 1;
  }
  .approval_btn {
    display: flex;
    justify-content: flex-end;
    .el-button {
      width: 80px;
      height: 32px;
      line-height: 32px;
      border-radius: 6px;
      padding: 0;
      &.el-button--primary {
        background: #0988fb;
        border-color: #0988fb;
      }
      &.el-button--warning {
        background: #ff8d1a;
        border-color: #ff8d1a;
      }
      &.el-button--default {
        border-color: #a6a6a6;
        color: #383838;
        background: #fff;
      }
      & + .el-button {
        margin-left: 12px;
      }
    }
  }
  .block_item {
    background: #fff;
    padding: 15px;
    height: calc(100vh - 151px);
    overflow-y: auto;
    overflow-x: hidden;
    &:not(:first-child) {
      margin-top: 15px;
    }
    .block_top {
      padding-bottom: 9px;
      border-bottom: 1px solid #e5e5e5;
      margin-bottom: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
    }
    :deep(.el-row) {
      .el-col {
        &.el-col-8 {
          width: auto;
        }
        div {
          margin-bottom: 16px;
          font-size: 14px;
          min-width: 300px;
          span {
            color: #808080;
          }
        }
      }
    }
    :deep(.el-table) {
      th.el-table__cell.is-leaf,
      td.el-table__cell {
        text-align: center;
        font-size: 12px;
      }
      th.el-table__cell {
        font-weight: bold;
      }
      .el-tag {
        font-size: 10px;
      }
    }
  }
  .detail_r {
    margin-left: 15px;
    width: 367px;
    .order_track {
      background: #fff;
      padding: 10px 16px;
      height: calc(100vh - 80px);
      overflow: auto;
      .order_top {
        margin-bottom: 0;
        padding-bottom: 8px;
        border-bottom: 1px solid #e5e5e5;
      }
      .track_list {
        padding: 11px 12px 0;
        .track_item {
          margin-bottom: 11px;
          .create_time {
            color: #808080;
            line-height: 18px;
            font-size: 12px;
            margin-bottom: 2px;
          }
          .track_cont {
            font-size: 14px;
            line-height: 21px;
            margin: 2px 0;
            span {
              margin: 0 8px;
            }
            .green {
              color: #00baad;
            }
            .red {
              color: #d43030;
            }
            .primary {
              color: #2a82e4;
            }
          }
        }
      }
    }
  }
}
:deep(.dialog_center) {
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    padding: 16px 17px;
  }
  .reject_reason {
    padding-left: 27px;
    margin-bottom: 22px;
    .el-checkbox {
      width: 250px;
      margin-bottom: 18px;
      .el-checkbox__inner {
        width: 18px;
        height: 18px;
        border-radius: 0;
        border-color: #a6a6a6;
        &::after {
          width: 6px;
          top: 2px;
          left: 4px;
        }
      }
      .el-checkbox__label {
        color: #383838;
        padding-left: 14px;
      }
      &.is-checked {
        .el-checkbox__inner {
          border-color: #0988fb;
          background-color: #0988fb;
        }
      }
    }
    .el-textarea__inner {
      resize: none;
    }
  }
}
</style>
